<template>
  <view class="pt-30" v-if="listData && listData.length">
    <train-list-item v-for="item in listData" :key="item.trainPlanId" :data="item" @click="navigateTo(item)" />
  </view>
  <empty v-else></empty>
</template>

<script>
import { getTrainingList } from '@/api/educational-training/trainingTasks'
import { DEFAULT_POST_URL } from './constant'
import { mapGetters } from 'vuex'
import TrainListItem from './components/TrainListItem'
import dayjs from 'dayjs'
import Empty from '@/components/cu-empty/index.vue'

const formatTime = (time) => dayjs(time).format('YYYY/MM/DD HH:mm')

export default {
  name: 'training-tasks',

  components: {
    TrainListItem,
    Empty
  },

  props: {},

  data() {
    return {
      pageNum: 1,
      total: 0,
      listData: []
    }
  },

  computed: {
    ...mapGetters(['userId'])
  },

  watch: {},

  created() {},

  mounted() {},

  destroyed() {},

  onNavigationBarButtonTap() {
    uni.navigateTo({
      url: `/pages/work/training-tasks/trainingRecord`
    })
  },
  onShow() {
    this.initData()
  },
  onPullDownRefresh() {
    this.initData()
  },
  onReachBottom() {
    this.pageNum++
    this.getlist()
  },

  methods: {
    initData() {
      this.pageNum = 1
      this.total = null
      this.getlist()
    },
    getlist() {
      const formatRows = (rows) =>
        rows.map((item) => ({
          trainPlanId: item.taskId,
          trainName: item.planName,
          trainStartTime: formatTime(item.startTime),
          trainEndTime: formatTime(item.endTime),
          trainDuration: item.trainDuration,
          trainLearnedDuration: item.trainLearnedDuration,
          trainDurationLabel: item.trainDurationLabel,
          trainLearnedDurationLabel: item.trainLearnedDurationLabel,
          courseStatus: item.courseStatus
        }))
      if (!this.total || this.total > this.listData.length) {
        getTrainingList({
          pageNum: this.pageNum,
          planMethod: 1
        }).then((res) => {
          if (this.pageNum === 1) {
            this.listData = formatRows(res.rows)
          } else {
            this.listData.push(...formatRows(res.rows))
          }
          this.total = res.total
          uni.stopPullDownRefresh()
        })
      }
    },
    navigateTo({ trainPlanId, trainName }) {
      uni.navigateTo({
        url: `/pages/work/training-tasks/content?trainPlanId=${trainPlanId}&pageName=${trainName}`
      })
    }
  }
}
</script>

<style scoped lang="scss" type="text/scss"></style>
